package org.dczl.system.service.impl;


import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dczl.common.mybatis.core.page.PageQuery;
import org.dczl.common.mybatis.core.page.TableDataInfo;
import org.dczl.system.domain.vo.DpDevice;
import org.dczl.system.mapper.DpDeviceMapper;
import org.dczl.system.service.IDpDeviceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Collection;

/**
 * 设备Service业务层处理
 *
 * @author jia
 * @date 2025-04-24
 */
@RequiredArgsConstructor
@Service
public class DpDeviceServiceImpl implements IDpDeviceService {

    private final DpDeviceMapper baseMapper;

    /**
     * 查询设备
     */
    @Override
    public DpDevice queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询设备列表
     */
    @Override
    public TableDataInfo<DpDevice> queryPageList(DpDevice bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DpDevice> lqw = buildQueryWrapper(bo);
        Page<DpDevice> result = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询设备列表
     */
    @Override
    public List<DpDevice> queryList(DpDevice bo) {
        LambdaQueryWrapper<DpDevice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<DpDevice> buildQueryWrapper(DpDevice bo) {
        LambdaQueryWrapper<DpDevice> lqw = Wrappers.lambdaQuery();
        lqw.eq(Validator.isNotEmpty(bo.getDeviceId()), DpDevice::getDeviceId, bo.getDeviceId());
        lqw.like(Validator.isNotEmpty(bo.getDeviceName()), DpDevice::getDeviceName, bo.getDeviceName());
        return lqw;
    }

    /**
     * 新增设备
     */
    @Override
    @Transactional
    public Boolean insertByBo(DpDevice bo) {
        boolean flag = baseMapper.insert(bo) > 0;
        if (flag) {
            bo.setId(bo.getId());
        }
        return flag;
    }

    /**
     * 修改设备
     */
    @Override
    @Transactional
    public Boolean updateByBo(DpDevice bo) {
        return baseMapper.updateById(bo) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DpDevice entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除设备
     */
    @Override
    @Transactional
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
